part of '../page.dart';

const _kDivisionCount = 5;
const _kSegmentLength = 1 / (_kDivisionCount - 1);

class _SpeakingRateSlider extends StatefulWidget {
  const _SpeakingRateSlider({
    required this.value,
    required this.onChangeEnd,
  });

  final double value;
  final ValueChanged<double> onChangeEnd;

  @override
  _SpeakingRateSliderState createState() => _SpeakingRateSliderState();
}

class _SpeakingRateSliderState extends State<_SpeakingRateSlider> with ScreenUtilMixin {
  late double _value;

  double _processValue(double value) {
    final magnetizationRadius = 0.05 / widthScaleFactor;
    final closestBreakPointIndex = (value / _kSegmentLength).round();
    final closestBreakPoint = closestBreakPointIndex * _kSegmentLength;

    if ((value - closestBreakPoint).abs() < magnetizationRadius) {
      return closestBreakPoint;
    } else {
      return value;
    }
  }

  @override
  void didUpdateWidget(_SpeakingRateSlider oldWidget) {
    super.didUpdateWidget(oldWidget);

    if (oldWidget.value != widget.value) {
      _value = _processValue(widget.value);

      if (widget.value != _value) {
        widget.onChangeEnd(_value);
      }
    }
  }

  @override
  void initState() {
    super.initState();

    _value = _processValue(widget.value);

    if (widget.value != _value) {
      widget.onChangeEnd(_value);
    }
  }

  @override
  Widget build(BuildContext context) {
    return CupertinoSlider(
      value: _value,
      activeColor: CoreTheme.of(context).primaryColor,
      onChanged: (value) {
        setState(() {
          _value = _processValue(value);
        });
      },
      onChangeEnd: (_) {
        widget.onChangeEnd(_value);
      },
      min: 0.0,
      max: 1.0,
    );
  }
}
